import React, { Component } from 'react'
//Count的容器组件
import {createIncrementAction,createDecrementAction,createAsyncAction} from '../../redux/count_action'
//引入UI组件
//引入connect连接UI组件和reduce
import {connect} from 'react-redux'
//函数mapStateToProps的返回值对象中的key作为传递给UI组件的props中的key，value就作为传递给UI组件的props中的value，传递状态
// function mapStateToProps(state){
//   return {count:state}
// }
//函数mapDispatchToProps的返回值对象中的key作为传递给UI组件的props中的key，value就作为传递给UI组件的props中的value，传递操作状态的方法
// function mapDispatchToProps(dispatch){
//   return {
//     jia:num => dispatch(createIncrementAction(num)),
//     jian:num => dispatch(createDecrementAction(num)),
//     jiasync:(num,time) => dispatch(createAsyncAction(num,time)),
//    }
// }

//暴露此容器组件
// export default connect(mapStateToProps,mapDispatchToProps)(CountUI)

//------------------------------------------------------------------------------------------------
//简写形式
//定义Count为UI组件
class Count extends Component {
  incrementCount=()=>{
    const {value}=this.selectNumber
    this.props.jia(value*1)
  }
  decrementCount=()=>{
    const {value}=this.selectNumber
    this.props.jian(value*1)
  }
  incrementCountIfOdd=()=>{
    const {value}=this.selectNumber
    if(this.props.count%2===0){
      this.props.jia(value*1)
    }
  }
  incrementCountAsync=()=>{
    const {value}=this.selectNumber
    this.props.jiasync(value*1,1000)
  }
  render() {
    console.log('UI组件接收到容器组件的数据是',this.props);
    return (
      <div>
        <h1>当前求和为:{this.props.count}</h1>
        <select ref={c=>this.selectNumber=c}>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
        </select>&nbsp;
        <button onClick={this.incrementCount}>+</button>&nbsp;
        <button onClick={this.decrementCount}>-</button>&nbsp;
        <button onClick={this.incrementCountIfOdd}>偶数时再加</button>
        <button onClick={this.incrementCountAsync}>等待完再加</button>
      </div>
    )
  }
}

export default connect(
  state=>({count:state}),
  {
    jia:createIncrementAction,//createIncrementAction这些函数执行后返回的是action对象，此时不需要使用dispatch分发给reducer，react-redux会自动分发
    jian:createDecrementAction,
    jiasync:createAsyncAction
  }
)(Count)